package com.du.ichat;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v4.app.DialogFragment;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.du.ichat.databinding.ActivitySignUpBinding;
import com.du.ichat.dialog.AvatarSelectDialog;
import com.du.ichat.retrofit.bean.SignupBean;
import com.du.ichat.retrofit.service.UserService;
import com.du.ichat.utils.AvatarUtils;
import com.du.ichat.utils.BaseActivity;
import com.du.ichat.utils.CheckSumBuilder;
import com.du.ichat.utils.RetrofitUtil;
import com.du.ichat.utils.Utils;


import java.io.File;
import java.io.FileNotFoundException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Date;
import java.util.Random;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.du.ichat.App.appKey;
import static com.du.ichat.App.appSecret;

public class SignUpActivity extends BaseActivity {
    private AvatarSelectDialog avatarSelectDialog;
    private FullDialog fullDialog;
    private ActivitySignUpBinding binding;
    private boolean etUsernameHasWord,etPasswordHasWord,etNicknameHasWord;
    private AvatarUtils avatarUtils;
    private File cutFile;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this , R.layout.activity_sign_up);
        avatarUtils = new AvatarUtils(this);
        avatarSelectDialog = new AvatarSelectDialog();
        fullDialog = new FullDialog();
        binding.signupColseBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        binding.usernameClearBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                binding.etUsername.setText("");
                view.setVisibility(View.GONE);
                setLoginBtnMode(false);
                etUsernameHasWord = false;
            }
        });
        binding.passwordClearBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                binding.etPassword.setText("");
                view.setVisibility(View.GONE);
                setLoginBtnMode(false);
                etPasswordHasWord = false;
            }
        });

        binding.nicknameClearBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                binding.etNickname.setText("");
                view.setVisibility(View.GONE);
                setLoginBtnMode(false);
                etNicknameHasWord = false;
            }
        });


        binding.etUsername.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                ChangeLineColor(binding.line1 , b);
                if(b){
                    if(!TextUtils.isEmpty(binding.etUsername.getText().toString())){
                        binding.usernameClearBtn.setVisibility(View.VISIBLE);
                    }
                }else{
                    binding.usernameClearBtn.setVisibility(View.GONE);
                }
            }
        });
        binding.etUsername.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if(!TextUtils.isEmpty(charSequence)){
                    binding.usernameClearBtn.setVisibility(View.VISIBLE);
                    etUsernameHasWord = true;
                }else{
                    etUsernameHasWord = false;
                }

                if(etUsernameHasWord&&etPasswordHasWord&&etNicknameHasWord){
                    setLoginBtnMode(true);
                }else{
                    setLoginBtnMode(false);
                }

            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        binding.etPassword.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                ChangeLineColor(binding.line2 , b);
                if(b){
                    if(!TextUtils.isEmpty(binding.etPassword.getText().toString())){
                        binding.passwordClearBtn.setVisibility(View.VISIBLE);
                    }
                }else{
                    binding.passwordClearBtn.setVisibility(View.GONE);
                }
            }
        });

        binding.etPassword.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if(!TextUtils.isEmpty(charSequence)){
                    binding.passwordClearBtn.setVisibility(View.VISIBLE);
                    etPasswordHasWord = true;
                }else{
                    etPasswordHasWord = false;
                }

                if(etUsernameHasWord&&etPasswordHasWord&&etNicknameHasWord){
                    setLoginBtnMode(true);
                }else{
                    setLoginBtnMode(false);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        binding.etNickname.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                ChangeLineColor(binding.line3 , b);
                if(b){
                    if(!TextUtils.isEmpty(binding.etNickname.getText().toString())){
                        binding.nicknameClearBtn.setVisibility(View.VISIBLE);
                    }
                }else{
                    binding.nicknameClearBtn.setVisibility(View.GONE);
                }
            }
        });

        binding.etNickname.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if(!TextUtils.isEmpty(charSequence)){
                    binding.nicknameClearBtn.setVisibility(View.VISIBLE);
                    etNicknameHasWord = true;
                }else{
                    etNicknameHasWord = false;
                }

                if(etUsernameHasWord&&etPasswordHasWord&&etNicknameHasWord){
                    setLoginBtnMode(true);
                }else{
                    setLoginBtnMode(false);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        binding.signupBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                fullDialog.showNow(getSupportFragmentManager() , "signuploading");
                String username = binding.etUsername.getText().toString();
                String password = binding.etPassword.getText().toString();
                String  nickname = binding.etNickname.getText().toString();
                String contentType = "application/x-www-form-urlencoded;charset=utf-8";
                final String nonce = new Random().nextInt(1000000) + "";
                final String curTime = String.valueOf((new Date()).getTime() / 1000L);
                final String checkSum = CheckSumBuilder.getCheckSum(appSecret, nonce ,curTime);
                password = CheckSumBuilder.getMD5(password);
                RetrofitUtil.create(UserService.class).signup(appKey , nonce , curTime ,checkSum ,contentType ,username , password , nickname).enqueue(new Callback<SignupBean>() {
                    @RequiresApi(api = Build.VERSION_CODES.M)
                    @Override
                    public void onResponse(Call<SignupBean> call, Response<SignupBean> response) {

                        SignupBean result = response.body();
                        if(result.getCode() == 200){
                            uploadAvatar(result.getInfo().getAccid());
                        }else{
                            fullDialog.dismiss();
                            showErrorMsg(result.getCode());
                        }
                    }

                    @Override
                    public void onFailure(Call<SignupBean> call, Throwable t) {
                        fullDialog.dismiss();
                        t.printStackTrace();
                        toast("注册失败，请重试");
                    }
                });
            }
        });

        binding.ivSignUpAvatar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                avatarSelectDialog.show(getSupportFragmentManager() , "dialog");
            }
        });



        avatarSelectDialog.setAvatarDialogListener(new AvatarSelectDialog.AvatarSelectDialogInterface() {
            @Override
            public void selectPhoto() {
                avatarUtils.selectPhoto();
            }

            @Override
            public void takePhoto() {
                avatarUtils.cameraPic();
            }
        });

    }



    private void setLoginBtnMode(boolean canClick){
        binding.signupBtn.setClickable(canClick);
        if(canClick){
            binding.signupBtn.setBackgroundColor(Color.parseColor("#1aad19"));
            binding.signupBtn.setTextColor(Color.WHITE);
        }else{
            binding.signupBtn.setBackgroundColor(Color.parseColor("#9bd69b"));
            binding.signupBtn.setTextColor(Color.parseColor("#b9e2b9"));
        }
    }

    private void ChangeLineColor(View line , boolean focus){
        if(focus){
            line.setBackgroundColor(Color.parseColor("#1aad19"));
        }else{
            line.setBackgroundColor(Color.parseColor("#d8d8d8"));
        }
    }

    private void showErrorMsg(int code){
        String msg = "注册失败";
        switch (code){
            case 414:
                msg = msg + ",账号已存在";
                break;
        }
        toast(msg);
    }

    @SuppressLint("ValidFragment")
    public static class FullDialog extends DialogFragment {
        @Nullable
        @Override
        public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
            this.setCancelable(false);
            View view  = inflater.inflate(R.layout.dialog_login_loading , null , false);
            TextView tv = view.findViewById(R.id.dialog_tv);
            tv.setText("正在注册...");
            return view;
        }
    }



    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.e("tag" , "resultcode : " + resultCode);
        if (resultCode == RESULT_OK){
            switch (requestCode){
                case 0: //从相册图片后返回的uri
                    //启动裁剪
                    startActivityForResult(avatarUtils.CutForPhoto(data.getData()),3);
                    break;
                case 1: //相机返回的 uri
                    //启动裁剪
                    String path = getExternalCacheDir().getPath();
                    String name = "output.png";
                    startActivityForResult(avatarUtils.CutForCamera(path,name),3);
                    break;
                case 3:
                    try {
                        //获取裁剪后的图片，并显示出来
                        Bitmap bitmap = BitmapFactory.decodeStream(
                                getContentResolver().openInputStream(avatarUtils.getmCutUri()));
                        cutFile = new File(new URI(avatarUtils.getmCutUri().toString()));
                        Log.e("tag" , "file : " + cutFile.getAbsolutePath());
                        Log.e("tag" , "file exeit: " + cutFile.exists());
                        if(!cutFile.exists()){
                            Utils.copyDefaultAvatarFile(this);
                        }
                        binding.ivSignUpAvatar.setPadding(0,0,0,0);
                        binding.ivSignUpAvatar.setImageBitmap(bitmap);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (URISyntaxException e) {
                        e.printStackTrace();
                    }
                    break;
            }
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    private void uploadAvatar(final String accid){
        File localFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getPath(),
                    CheckSumBuilder.getMD5(accid) + ".png");
        cutFile.renameTo(localFile);
        fullDialog.dismiss();
        toast("注册成功");
        finish();

    }

}
